package com.dmai.capacity.platform.gateway.listener;

import com.dmai.capacity.platform.common.model.GatewayLog;
import com.dmai.capacity.platform.common.model.OauthUserPackage;
import com.dmai.capacity.platform.common.utils.SpringUtil;
import com.dmai.capacity.platform.gateway.constants.HandleResultEnum;
import com.dmai.capacity.platform.gateway.constants.RedisKeyConstant;
import com.dmai.capacity.platform.oauth.common.service.IGatewayLogService;
import com.dmai.capacity.platform.oauth.common.service.ICapabilityPackageService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class GatewayEventListener {

    @Autowired
    private IGatewayLogService gatewayLogService;

    @Autowired
    private ICapabilityPackageService resourcePackageService;

    @Autowired
    private Redisson redisson;


    /**
     * 消费请求事件
     *
     * @param event
     */
    @EventListener({GatewayLog.class})
    public void comsumer(GatewayLog event) {
//  CompletableFuture.runAsync(() -> {
        if (event.getPackageId() != 0) {
            // 缓存客户入队请求数量
            RBucket<List<OauthUserPackage>> cache = redisson.getBucket(RedisKeyConstant.CACHE_USER_PACKAGE_PREFIX + ":" + event.getUserid() + ":" + event.getCapabilityId());
            if (cache.isExists()) {
                RAtomicLong atomicLong = redisson.getAtomicLong(RedisKeyConstant.CACHE_USER_REQUEST_COUNT_PREFIX + ":" + event.getUserid() + ":" + event.getCapabilityId());
                if (!atomicLong.isExists()) {
                    atomicLong.incrementAndGet();
                    atomicLong.expire(cache.remainTimeToLive() / 1000, TimeUnit.SECONDS);
                } else {
                    atomicLong.incrementAndGet();
                }
            }
        }

        // 记录请求
        gatewayLogService.save(event);


        if (event.getAsync() == null || !event.getAsync()) {
            // 非异步请求，直接将处理成功的扣减资源包
            if (event.getHandleResult() == HandleResultEnum.SUCCESS.getCode()) {
                // 更新资源包套餐
                GatewayLog log = gatewayLogService.get(event.getTraceId());
                if (log.getPackageId() > 0) {
                    // packageId>0 表示本次请求走资源包，需要更新资源包使用情况
                    resourcePackageService.deduction(log.getCapabilityId(), log.getPackageId());
                }
            }
        }
//   }, taskExecutor);
    }

}